package com.defysoft.waukids.intro;

import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.defysoft.waukids.BaseActivity;
import com.defysoft.waukids.R;
import com.defysoft.waukids.attend.Attend_SelectDay_A;
import com.defysoft.waukids.attend.Attend_SelectMember_A;
import com.defysoft.waukids.notice.Notice_Main_A;
import com.defysoft.waukids.slide.Member_Information_A;
import com.defysoft.waukids.slide.Member_Notifications_A;
import com.defysoft.waukids.slide.Slide_Field_Trip_A;
import com.defysoft.waukids.slide.Slide_MemberStudent_Connect_A;

public class Intro_Main_A extends BaseActivity implements OnClickListener {
	private SharedPreferences school;
	private SharedPreferences member;
	private SharedPreferences student;
	private SharedPreferences school_class;
	private SharedPreferences check_notice;
	ActionBarDrawerToggle toggle;
	DrawerLayout drawerLayout;
	Fragment fragment;
	String[] listset;
	ListView listView;
	ImageView newiv;
	View drawer;

	final int MAIN_THREAD = 1;
	final int LOGOUT_THREAD = 2;
	final int MEMBER_SECESSION_THREAD = 3; // 탈퇴

	final int FAIL_SECESSION = 4;
	final int SUCCESS_SECESSION = 5;
	final int FAIL_LOGOUT = 6;
	final int SUCCESS_LOGOUT = 7;
	final int HAVE_CLASS_TEACHER = 8;
	final int HAVE_CLASS_STDENT = 9;
	final int NON_CLASS = 10;

	// 백키2번눌렀을때 종료.
	BackPressCloseHandler backPressCloseHandler;
	
	boolean drawerCheck = false;
	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		super.onActivityResult(arg0, arg1, arg2);

		if (arg1 == SLIDE_MEMBERSTUDENT_CONNECT) {
			startActivity(new Intent(this, Intro_Intro_A.class));
			finish();
		}
		if (arg1 == SLIDE_FIELD_TRIP_BACK) { // 현장학습 MESSAGE내용.

		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_intro__main_);
		setStartData();

		registerReceiver(mToastMessageReceiver, new IntentFilter(
				"com.defysoft.waukids.TOAST_MESSAGE"));
		if (!member.getString("Mem_Rank", "0").equals("1")) { // 선생님, 부모이면.
			startNetwork(MAIN_THREAD);
		} else {
			endDIal();// 원장님.
			fragment = new Intro_Button_F(1);
			getSupportFragmentManager().beginTransaction()
					.replace(R.id.MAIN_FRAGMENT, fragment)
					.commitAllowingStateLoss();
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		check_notice = getSharedPreferences("check_notice", MODE_PRIVATE);
		if (check_notice.getInt("notice_count", 0) != 0) {
			newiv.setVisibility(View.VISIBLE);
		} else {
			newiv.setVisibility(View.GONE);
		}
	}

	@Override
	public void setStartData() {
		// TODO Auto-generated method stub
		super.setStartData();
		startDIal();
		member = getSharedPreferences("member", MODE_PRIVATE);
		school = getSharedPreferences("school", MODE_PRIVATE);
		student = getSharedPreferences("student", MODE_PRIVATE);

		newiv = (ImageView) findViewById(R.id.MAIN_NOTICE_NEW);
		findViewById(R.id.MAIN_NOTICE).setOnClickListener(this); // 공지
		findViewById(R.id.MAIN_ATTEND).setOnClickListener(this); // 출석
		findViewById(R.id.MAIN_PHOTO).setOnClickListener(this); // 앨범
		drawerLayout = (DrawerLayout) findViewById(R.id.MAIN_DRAWER);
		Toolbar toolbar = (Toolbar) findViewById(R.id.MAIN_TOOL); // 액션바 기능의 툴바.
		school_class = getSharedPreferences("school_class", MODE_PRIVATE);
		listView = (ListView) findViewById(R.id.MAIN_SLID);

		((TextView) findViewById(R.id.MAIN_TITLE)).setText(school.getString(
				"Sch_Name", "WAUKIDS"));

		// toolbar 구성.
		toolbar.setNavigationIcon(R.drawable.ic_drawer); // drawer버튼세팅.
		// toggle세팅.
		toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar,
				R.string.app_name, R.string.hello_world) {
			@Override
			public void onDrawerClosed(View drawerView) {
				super.onDrawerClosed(drawerView);
				drawerCheck = false;
			}

			@Override
			public void onDrawerOpened(View drawerView) {
				super.onDrawerOpened(drawerView);
				drawerCheck = true;
			}
		};
		drawerLayout.setDrawerListener(toggle);
		if (member.getString("Mem_Rank", "").equals("3")) {
			listset = new String[] { "커뮤니티", "정보수정", "푸시옵션", "로그아웃", "회원탈퇴",
					"자녀등록", "자녀삭제" };
		} else if (member.getString("Mem_Rank", "").equals("2")) {
			listset = new String[] { "커뮤니티", "정보수정", "푸시옵션", "로그아웃", "회원탈퇴",
					"현장학습" };
		} else if (member.getString("Mem_Rank", "").equals("1")) {
			listset = new String[] { "커뮤니티", "정보수정", "푸시옵션", "로그아웃", "회원탈퇴" };
		}
		listView.setAdapter(new SlidAdapter());
		listView.setDivider(null);
		// 뒤로두번눌리면 종료
		backPressCloseHandler = new BackPressCloseHandler(this);

		drawer = (View)findViewById(R.id.MAIN_DRAWER_SLIDE);
	}

	@Override
	public void startThread(int choice) {
		super.startThread(choice);
		final int cho = choice;
		if (firstThread != null) {
			firstThread.interrupt();
		}
		firstThread = new Thread(new Runnable() {
			@Override
			public void run() {
				switch (cho) {
				case MAIN_THREAD:
					mainThread();
					break;
				case LOGOUT_THREAD:
					logoutThread();
					break;
				case MEMBER_SECESSION_THREAD:
					secessionThread();
					break;
				}
			}
		});
		firstThread.start();
		startDIal();
	}

	@Override
	protected void handlingMessage(Message _message) {
		// TODO Auto-generated method stub
		super.handlingMessage(_message);
		SharedPreferences.Editor editor;
		Intent i;
		switch (_message.what) {
		case CATCH_EXCEPTION: // thread 에러 메세지
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			Toast.makeText(this, (String) _message.obj, Toast.LENGTH_SHORT)
					.show();
			break;
		case NON_CLASS: // 선생님이 반배정이 안됨.
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			Toast.makeText(this, (String) _message.obj, Toast.LENGTH_SHORT)
					.show();
			break;
		case HAVE_CLASS_TEACHER: // 반배정이됨.
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			fragment = new Intro_Button_F(2);
			getSupportFragmentManager().beginTransaction()
					.replace(R.id.MAIN_FRAGMENT, fragment)
					.commitAllowingStateLoss();
			setPreferencesclass((String) _message.obj); // 학원정보 입력.
			// 선생님
			break;
		case HAVE_CLASS_STDENT: // 보호자
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			setPreferencesclass((String) _message.obj); // 학원정보 입력.
			fragment = new Intro_Status_F(
					student.getString("PK_Stu_Code", "0"), student.getString(
							"FK_Sch_Stu_Code", "0"));
			getSupportFragmentManager().beginTransaction()
					.replace(R.id.MAIN_FRAGMENT, fragment)
					.commitAllowingStateLoss(); // 보호자
			break;
		case SUCCESS_LOGOUT: // 로그아웃UUID삭제 성공.
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			editor = member.edit();
			editor.clear();
			editor.commit();
			i = new Intent(this, Intro_Intro_A.class);
			startActivity(i);
			finish();

			break;
		case FAIL_LOGOUT: // 로그아웃 UUID삭제 실패.
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			Toast.makeText(this, (String) _message.obj, Toast.LENGTH_SHORT)
					.show();
			break;
		case SUCCESS_SECESSION: // 회원탈퇴 성공.
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			Toast.makeText(this, "회원탈퇴 되었습니다.", Toast.LENGTH_SHORT).show();
			editor = member.edit();
			editor.clear();
			editor.commit();
			i = new Intent(this, Intro_Intro_A.class);
			startActivity(i);
			finish();
			break;
		case FAIL_SECESSION: // 회원탈퇴 실패.
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			Toast.makeText(this, (String) _message.obj, Toast.LENGTH_SHORT)
					.show();
			break;

		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.MAIN_NOTICE: // 공지사항
			startActivity(new Intent(this, Notice_Main_A.class));
			break;
		case R.id.MAIN_ATTEND: // 출결관리
			if (member.getString("Mem_Rank", "").equals("3")) {
				startActivity(new Intent(this, Attend_SelectDay_A.class)
						.putExtra(INTENT_EXTRA_ATTEND_PK_STU_CODE,
								student.getString("PK_Stu_Code", "")).putExtra(
								INTENT_EXTRA_ATTEND_STU_NAME,
								student.getString("Stu_Name", "")));
			} else {
				startActivity(new Intent(this, Attend_SelectMember_A.class));
			}
			break;
		case R.id.MAIN_PHOTO: // 앨범
			Toast.makeText(this, "아직 준비중입니다.", Toast.LENGTH_LONG).show();
			fragment.onResume();
			break;
		}
	}

	protected void mainThread() {
		JSONObject jsonObject = null;
		try {
			if (member.getString("Mem_Rank", "").equals("2")) { // 선생님.

				jsonObject = new JSONObject(publicHttpCallback(
						HTTP_SELECT_MYCLASS,
						"code=" + member.getString("FK_Cla_Mem_Code", "")));
				if (jsonObject.getBoolean("success")) {

					onNetworkCallback(HAVE_CLASS_TEACHER,
							jsonObject.getString("payload"));

				} else {
					onNetworkCallback(NON_CLASS,
							jsonObject.getString("message"));
				}
			} else if (member.getString("Mem_Rank", "").equals("3")) { // 보호자.
				jsonObject = new JSONObject(publicHttpCallback(
						HTTP_SELECT_MYCLASS,
						"code=" + student.getString("FK_Cla_Stu_Code", "")));
				if (jsonObject.getBoolean("success")) {
					onNetworkCallback(HAVE_CLASS_STDENT,
							jsonObject.getString("payload"));

				} else {
					onNetworkCallback(NON_CLASS,
							jsonObject.getString("message"));
				}
			} else {
				onNetworkCallback(NON_CLASS, "통신실패");
			}

		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION, "main" + e.toString());
		}
		;
	}

	protected void logoutThread() { // 로그아웃스레드.
		JSONObject jsonObject = null;
		try {
			jsonObject = new JSONObject(publicHttpCallback(HTTP_MEMBER_LOGOUT,
					"PK_Mem_Email=" + member.getString("PK_Mem_Email", "")));
			if (jsonObject.getBoolean("success")) {
				onNetworkCallback(SUCCESS_LOGOUT,
						jsonObject.getString("payload"));
			} else {
				onNetworkCallback(FAIL_LOGOUT, jsonObject.getString("message"));
			}
		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION, "main" + e.toString());
		}
		;
	}

	protected void secessionThread() { // 회원탈퇴스레드.
		JSONObject jsonObject = null;

		try {

			jsonObject = new JSONObject(publicHttpCallback(
					HTTP_MEMBER_SECESSION,
					"PK_Mem_Email=" + member.getString("PK_Mem_Email", "")
							+ "&Mem_Rank=" + member.getString("Mem_Rank", "")));

			if (jsonObject.getBoolean("success")) {
				onNetworkCallback(SUCCESS_SECESSION,
						jsonObject.getString("payload"));
			} else {
				onNetworkCallback(FAIL_SECESSION,
						jsonObject.getString("message"));
			}
		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION, "main" + e.toString());
		}
		;
	}

	private void setPreferencesclass(String msg) {
		try {
			JSONObject jsonObject = new JSONObject(msg);

			SharedPreferences.Editor editora = school_class.edit();
			editora.putString("PK_Cla_Code",
					jsonObject.getString("PK_Cla_Code"));
			editora.putString("FK_Sch_Cla_Code",
					jsonObject.getString("FK_Sch_Cla_Code"));
			editora.putString("Cla_Name", jsonObject.getString("Cla_Name"));
			editora.putString("Cla_Info", jsonObject.getString("Cla_Info"));
			editora.commit();
		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION, "school" + e.toString());
		}
		;
	}

	class SlidAdapter extends ArrayAdapter<String> {	//슬라이드바 설정.

		public SlidAdapter() {
			super(Intro_Main_A.this, 0);
			// TODO Auto-generated constructor stub
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return listset.length;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			SlidHolder slidHolder;
			if (convertView == null) {
				slidHolder = new SlidHolder();
				convertView = getLayoutInflater().inflate(
						R.layout.intro_mainslide_row, null);
				slidHolder.tv = (TextView) convertView
						.findViewById(R.id.MAIN_SLIDEROW);
				convertView.setTag(slidHolder);

			} else {
				slidHolder = (SlidHolder) convertView.getTag();
			}
			slidHolder.tv.setText(listset[position]);
			final int pos = position;
			convertView.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent i;
					switch (pos) {
					case 0: // 커뮤니티
						Toast.makeText(Intro_Main_A.this, "아직 준비중입니다.",
								Toast.LENGTH_LONG).show();

						break;
					case 1: // 정보수정
						i = new Intent(Intro_Main_A.this,
								Member_Information_A.class).putExtra(
								"PK_Mem_Email",
								member.getString("PK_Mem_Email", ""));
						startActivityForResult(i, SLIDE_CONNECT);
						break;
					case 2: // 알림설정
						i = new Intent(Intro_Main_A.this,
								Member_Notifications_A.class).putExtra(
								"PK_Mem_Email",
								member.getString("PK_Mem_Email", ""));
						startActivityForResult(i, SLIDE_CONNECT);
						break;
					case 3: // 로그아웃
						logOut();
						break;
					case 4: // 회원탈퇴
						dialog_secession(1);
						break;
					case 5: // 자녀등록, 현장학습.
						if (member.getString("Mem_Rank", "").equals("3")) {
							i = new Intent(Intro_Main_A.this,
									Slide_MemberStudent_Connect_A.class)
									.putExtra("PK_Mem_Email", member.getString(
											"PK_Mem_Email", ""));

						} else { // 현장학습.
							i = new Intent(Intro_Main_A.this,
									Slide_Field_Trip_A.class)
									.putExtra(
											"FK_Cla_Mem_Code",
											member.getString("FK_Cla_Mem_Code",
													""))
									.putExtra(
											"FK_Sch_Mem_Code",
											member.getString("FK_Sch_Mem_Code",
													""))
									.putExtra(
											"Sch_Name",
											school.getString("Sch_Name",
													"WAUKIDS"))
									.putExtra(
											"Cla_Name",
											school_class.getString("Cla_Name",
													""));
						}
						startActivityForResult(i, SLIDE_CONNECT);
						break;
					case 6: // 자녀삭제
						i = new Intent(Intro_Main_A.this,
								Slide_DeleteStudent_A.class).putExtra(
								"PK_Mem_Email",
								member.getString("PK_Mem_Email", ""));
						startActivityForResult(i, SLIDE_CONNECT);
						break;
						
					}
				}
			});

			return convertView;
		}

		protected void dialog_secession(int i) { // 회원탈퇴 확인.
			AlertDialog.Builder builder = new AlertDialog.Builder(
					Intro_Main_A.this);
			builder.setMessage(
					"회원탈퇴 하겠습니까?\n한 번 탈퇴한 아이디는 동일 아이디로 재가입 하거나, 복구하는 것이 불가능 하오니, 탈퇴 시 유의하시기 바랍니다.")
					.setCancelable(false)
					.setPositiveButton("네",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									memberSecession();
									dialog.cancel();
								}
							})
					.setNegativeButton("아니오",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									dialog.cancel();
								}
							});
			AlertDialog alert = builder.create();
			alert.show();
		}
	}

	class SlidHolder {
		TextView tv;
	}

	// 로그아웃
	private void logOut() {
		AlertDialog.Builder builder = new AlertDialog.Builder(
				Intro_Main_A.this);
		builder.setMessage(
				"로그아웃 하겠습니까?")
				.setCancelable(false)
				.setPositiveButton("네",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								startNetwork(LOGOUT_THREAD);
								dialog.cancel();
							}
						})
				.setNegativeButton("아니오",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.cancel();
							}
						});
		AlertDialog alert = builder.create();
		alert.show();


	}

	// 회원탈퇴
	private void memberSecession() {
		startNetwork(MEMBER_SECESSION_THREAD);

	}

	// 백키 2번 눌렀을때 종료.
	public class BackPressCloseHandler {

		private long backKeyPressedTime = 0;
		private Toast toast;

		private Activity activity;

		public BackPressCloseHandler(Activity context) {
			this.activity = context;
		}

		public void onBackPressed() {
			if (System.currentTimeMillis() > backKeyPressedTime + 2000) {
				backKeyPressedTime = System.currentTimeMillis();

				showGuide();
				return;
			}
			if (System.currentTimeMillis() <= backKeyPressedTime + 2000) {
				activity.finish();
				toast.cancel();
			}
		}

		public void showGuide() {
			toast = Toast.makeText(activity, "\'뒤로\'버튼을 한번 더 누르시면 종료됩니다.",
					Toast.LENGTH_SHORT);
			toast.show();
		}
	}

	@Override
	public void onBackPressed() {
		// super.onBackPressed();
		drawerLayout.closeDrawer(drawer);
		if (!drawerCheck) {
			backPressCloseHandler.onBackPressed();
		}
	}

	private final BroadcastReceiver mToastMessageReceiver = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {
			fragment.onResume();
			if (intent.getBooleanExtra("notice", false)) {
				onResume();
			}
		}
	};

	
}// CLASS_END
